<?php

class Ext_XMLArraySerializer
{

	function serializeArray($topLevelTag, $topLevelAttributes, $array, $level = 0)
	{
		
		$isAssociative = $this->arrayIsAssociative($array);
		$indent  = str_repeat(" ", $level);
		$indent2 = ($isAssociative) ? str_repeat(" ", $level + 1) : $indent;

		$xml = "";
		$attributes = is_array($topLevelAttributes) ? $topLevelAttributes : array();
		foreach( $array as $key => $val )
		{
			if ( $isAssociative )
			{
				$tag = strtolower($key);
			} else {
				$tag = $topLevelTag;
			}
			if (is_scalar($val))
			{
				if ($key[0] == '@')
				{
					$attributes[substr($key,1)] = $val;
				} else if ( $tag == "#" )
				{
					$xml .= $val;
				} else {
					$xml .= $indent2 . "<$tag>$val</$tag>\n";
				}
			}
			if (is_array($val))
			{
				$xml .= $this->serializeArray( $tag, array(), $val, $level+1 );
			}
		}

		if ($isAssociative)
		{
			$attr_str = "";
			if ( count($attributes) > 0 )
			{
				foreach( $attributes as $k => $v )
				{
					$attr_str .= "$k=\"$v\" ";
				}
				$attr_str = substr( $attr_str, 0, strlen($attr_str)-1 );
				$content = $indent . "<$topLevelTag $attr_str";
			} else {
				$content = $indent . "<$topLevelTag";
			}
			if ($xml != "")
			{
				$content .= ">\n" . $xml;
				$content .= $indent . "</$topLevelTag>\n";
			} else {
				$content .= " />\n";
			}
		} else {
			$content = $xml;
		}

		return $content;
	}

	function arrayIsAssociative ($array)
	{
		if ( is_array($array) && ! empty($array) )
		{
			// now with whatever is left do the test
			for ( $iterator = count($array) - 1; $iterator; $iterator-- )
			{
				if ( ! array_key_exists($iterator, $array) ) { return true; }
			}
			return ! array_key_exists(0, $array);
		}
		return false;
	}
}
